package dao;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;

import dbUtil.JDBCUtils;
import entity.equip;
import entity.hero;
import entity.trammel;


public class trammel_dao {
	
	public void add(String sql){
		QueryRunner queryRunner =new QueryRunner(JDBCUtils.getDataSource());
		try {
			queryRunner.update(sql);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void delete(String sql){
		add(sql);
	}
	public void change(String sql){
		add(sql);
	}
	public List<trammel> select(String sql){
		QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
		List<trammel> trammels = null;
		try {
			trammels = queryRunner.query(sql,new BeanListHandler<>(trammel.class));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return trammels;
		
	}
	public trammel find_trammel_hero(trammel target){
		List<Integer> target_id=trammel_dao.find_trammel_hero_id(target.getTrammel_id());
		String id=null;
		String name=null;
		for(int i=0;i<target_id.size();i++){
			
			int temp=target_id.get(i);
			String sql="select hero_name from hero where hero_id=\""+temp+"\"";
			List<String> res=null;
			QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
			try {
				res=queryRunner.query(sql, new ColumnListHandler<String>());
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (i!=0) {
				id+=','+Integer.toString(temp);
				name+=','+res.get(0);
			}
			else{
				id=Integer.toString(temp);
				name=res.get(0);
			}
		}
		target.set_trammel_hero(name);
		target.set_trammel_hero_id(id);
		return target;
	}
	
	public static List<Integer> find_trammel_hero_id(int target_id){
		String sql="select hero_id from hero_trammel where trammel_id=\""+target_id+"\"";
		List<Integer> res=null;
		QueryRunner queryRunner=new QueryRunner(JDBCUtils.getDataSource());
		try {
			res=queryRunner.query(sql,new ColumnListHandler<Integer>());
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
	}
}

